import { Component, OnInit, Injector, ChangeDetectorRef, } from '@angular/core';
import { map } from 'rxjs/operators';
import { DetailBase } from 'app/modules/base/detail-base';
import { WhitelistService, WhitelistOptions } from '../../services/whitelist.service';
import { UsbAuthorizeService } from '../../services/usb-authorize.service';

@Component({
  selector: 'm-white-list',
  templateUrl: './white-list.component.html',
  styleUrls: ['./white-list.component.scss']
})
export class WhiteListComponent extends DetailBase implements OnInit {

  constructor(
    private injector: Injector,
    private whitelistService: WhitelistService,
    private service: UsbAuthorizeService,
    public changeDetectorRef: ChangeDetectorRef,) {
    super(injector);
  }

  searchKey: string = '';
  result$ = this.route.data.pipe(map((data) => data['list']));
 
  usbconf: any;
  ngOnInit() {
    this.service.getUsbConf().then((res:any)=>{
      this.usbconf = +res.message;
    })
    this.route.queryParamMap.subscribe((data) => {
      this.searchKey = data.get('keywords') || '';
    });
    this.service.usbEventer.subscribe((e) => {
      this.service.getUsbConf().then((res: any) => {
        this.usbconf = +res.message;
        this.changeDetectorRef.markForCheck();
        this.changeDetectorRef.detectChanges();
      });
    });
  }

  onSearchKey(key: string, exec: boolean) {
    if (this.searchKey == key) {
      return;
    }
    this.searchKey = key;
    if (!exec) {
      return;
    }
    this.startSearch();
  }

  startSearch() {
    let params: WhitelistOptions = { page: 1 };
    if (this.searchKey.length != 0) {
      params['keywords'] = this.searchKey;
    }
    this.router.navigate([this.router.url.split('?')[0]], {
      relativeTo: this.route,
      queryParams: params,
    });
  }

  refresh() {
    return this.router.navigateByUrl(this.router.url);
  }

  async removeWhitelist(id: number) {
    this.sweet.defaultOption.confirmButtonText = '移出'
    if ((await this.sweet.confirm('确定要移出白名单吗')).dismiss) {
      return;
    }
    await this.whitelistService.removeWhitelist(id);
    this.reload();
  }
}
